package steps;

import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;


import com.metodo_ahp.usuario.aplicacionmetodoahp.R;


import adapters.CriterioDefinicionAdapter;
import dialog.DlgCompararAlternativas;
import gestores.GestorModeloAHP;
import libreria.WizardStep;
import modelo.Item;

/**
 * Created by Usuario on 26/09/2014.
 */
public class step_1_def_criterios extends WizardStep implements View.OnClickListener, View.OnKeyListener{

    private Button btnNuevoCriterio;
    private ViewGroup layout;
    private ScrollView scvCriterios;
    private ListView lstCriterios;
    CriterioDefinicionAdapter adapter;

     GestorModeloAHP gestorModelo;

    public step_1_def_criterios() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gestorModelo = (GestorModeloAHP) getActivity().getApplicationContext();

    }


    /**
     * Sirve para asociar el layout al fragment.
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.step_1_lista_def_criterios, container, false);
    }

    /**
     * Fragment ya creado, layout ya asociado.
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        layout = (ViewGroup) this.getView().findViewById(R.id.contCriterios);

        btnNuevoCriterio = (Button) this.getView().findViewById(R.id.btnNuevoCriterio);
        btnNuevoCriterio.setOnClickListener(this);
        scvCriterios = (ScrollView) this.getView().findViewById(R.id.scvCriterios);
        //lstResultados = (ListView) getView().findViewById(R.id .lstViewCriterios);


        // adapter = new CriterioDefinicionAdapter(this, gestorModelo.getListaCriterios());
        //lstResultados.setAdapter(adapter);
        if(gestorModelo.getListaCriterios().size() > 0){
            cargarCriterios();
            addChild();
        }else{
            this.addChild();
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btnNuevoCriterio){
            int idCriterio = gestorModelo.getSizeMatrizBase(true); //Para buscar en la interfaz el txt correspondiente.
            EditText text = (EditText) this.getView().findViewById(idCriterio);
            String nombreCriterio = String.valueOf(((EditText) text).getText());

            gestorModelo.addItem(nombreCriterio, true); // Le pasamos el nombre y se ocupa de crear el criterio.
            // Create and show the dialog.
           // DialogFragment newFragment = DlgCompararAlternativas.newInstance(gestorModelo,idCriterio);

            //newFragment.show(getActivity().getFragmentManager(),"tag");
            this.addChild();
        }
    }



    private void addChild()
    {
        LayoutInflater inflater = LayoutInflater.from(this.getActivity());
        int id = R.layout.step_1_item_def_criterio;

        RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(id, null, false);
        EditText txtNombre = (EditText) relativeLayout.findViewById(R.id.txtDefCriterioNombre);
        txtNombre.setHint("Criterio");
        txtNombre.setId(gestorModelo.getSizeMatrizBase(true));
        txtNombre.setOnKeyListener(this);
        txtNombre.requestFocus();


        //layout params
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.topMargin = 2;
        relativeLayout.setPadding(2, 3, 5, 2);
        relativeLayout.setLayoutParams(params);
        ///////

        layout.addView(relativeLayout);
        layout.requestFocus();

        //scroll to last element
        //http://stackoverflow.com/questions/6438061/can-i-scroll-a-scrollview-programmatically-in-android
        scvCriterios.post(new Runnable() {
          public void run() {
           scvCriterios.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        ///////

    }

    public void cargarCriterios(){
        for (Item it:gestorModelo.getListaCriterios()){
            LayoutInflater inflater = LayoutInflater.from(this.getActivity());
            int id = R.layout.step_1_item_def_criterio;

            RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(id, null, false);
            EditText txtNombre = (EditText) relativeLayout.findViewById(R.id.txtDefCriterioNombre);
            txtNombre.setId(it.getId());
            txtNombre.setText(it.getNombre());
            txtNombre.setOnClickListener(this);

            //layout params
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.topMargin = 2;
            relativeLayout.setPadding(2, 3, 5, 2);
            relativeLayout.setLayoutParams(params);
            ///////

            layout.addView(relativeLayout);
        }
    }


    /**
     * Called when a hardware key is dispatched to a view. This allows listeners to
     * get a chance to respond before the target view.
     * <p>Key presses in software keyboards will generally NOT trigger this method,
     * although some may elect to do so in some situations. Do not assume a
     * software input method has to be key-based; even if it is, it may use key presses
     * in a different way than you expect, so there is no way to reliably catch soft
     * input key presses.
     *
     * @param v       The view the key has been dispatched to.
     * @param keyCode The code for the physical key that was pressed
     * @param event   The KeyEvent object containing full information about
     *                the event.
     * @return True if the listener has consumed the event, false otherwise.
     */
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_ENTER){
                EditText text = (EditText) v;
                int idCriterio = v.getId();
                String nombreCriterio = String.valueOf(((EditText) v).getText());

                gestorModelo.modificarItem(idCriterio,nombreCriterio,true);

                return true;
            }

        return false;
    }

}


